﻿using NewLife.Serialization;
using Datav.Design.IService;
using XCode;
using Zdap.Common;
using Zdap.Common.AutoMapper;
using Zdap.Common.Extensions;
using Zdap.Common.IdGenerate;
using Zdap.XCode.Service;

namespace Datav.Design.Service
{
    /// <summary>
    ///
    /// </summary>
    public class AIConfigService : BaseService<AIConfig, SaveConfigDto, AIConfigModel>, IAIConfigService
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public override async ValueTask<ResponseContext<long>> Save(SaveConfigDto dto, UserTicket currentUser)
        {
            if (dto.Id == 0)
            {
                dto.Id = IdWorker.NextId();
            }
            // var config = dto.MapTo<AIConfig>();
            var configDetails = new List<AIConfigDetail>();
            if (dto.DetailList != null && dto.DetailList.Any())
            {
                dto.DetailList.ForEach(detailItem =>
                {
                    var configDetailId = IdWorker.NextId();
                    var file = string.Empty;
                    if (detailItem.FileList != null && detailItem.FileList.Any())
                    {
                        file = JsonHelper.ToJson(detailItem.FileList);
                    }
                    var detail = detailItem.MapTo<AIConfigDetail>();
                    if (dto.Id == 0)
                        detail.Id = configDetailId;
                    detail.AIConfigId = dto.Id;
                    detail.File = JsonHelper.ToJson(detailItem.FileList);
                    CommonService.SetCommonPropertyTenantId(detail, currentUser);
                    configDetails.Add(detail);
                });
                dto.FileCount = dto.DetailList.Sum(s => s.FileList.Count());
                dto.QuestionCount = dto.DetailList.Count();
            }

            using (var tran1 = AIConfig.Meta.CreateTrans())
            {
                var data = base.Save(dto, currentUser);
                configDetails.Upsert(CommonService.GetEntityDataColumn<AIConfigDetail>());
                tran1.Commit();
                return await data;
            }
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        protected override async ValueTask<ResponseContext<bool>> AddValidate(SaveConfigDto dto)
        {
            var result = new ResponseContext<bool>();
            if (dto.DetailList.Any(s => string.IsNullOrEmpty(s.ReplyContent)))
            {
                return await Task.FromResult(result.SetError("回复内容需要做必填！"));
            }
            return await base.AddValidate(dto);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        protected override async ValueTask<ResponseContext<bool>> UpdateValidate(SaveConfigDto dto)
        {
            var result = new ResponseContext<bool>();
            if (dto.DetailList.Any(s => string.IsNullOrEmpty(s.ReplyContent)))
            {
                return await Task.FromResult(result.SetError("回复内容需要做必填！"));
            }
            return await base.UpdateValidate(dto);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public override async Task<ResponseContext<SaveConfigDto>> FindById(long Id)
        {
            var data = await base.FindById(Id);
            var configDetails = await AIConfigDetail.FindAllAsync(AIConfigDetail._.AIConfigId == Id);
            var details = new List<SaveConfigDetailDto>();

            configDetails.ForEach(s =>
            {
                var item = s.MapTo<SaveConfigDetailDto>();
                if (!string.IsNullOrEmpty(s.File))
                    item.FileList = JsonHelper.ToJsonEntity<List<ConfigFileDto>>(s.File);
                details.Add(item);
            });
            data.Data.DetailList = details;
            return await Task.FromResult(data);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="id"></param>
        /// <param name="user"></param>
        /// <returns></returns>
        public override async ValueTask<ResponseContext<bool>> Delete(long id, UserTicket user)
        {
            //DeleteConfig(id);
            var data = await base.Delete(id, user);
            AIConfigDetail.Delete($"AIConfigId ={id}");
            return await Task.FromResult(data);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="ProjectId"></param>
        /// <param name="keyword"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>

        public async Task<ReplayContentDto> SearchReplayContent(long ProjectId, string keyword, UserTicket currentUser)
        {
            if (string.IsNullOrWhiteSpace(keyword))
            {
                return null;
            }

            var configDetails = await AIConfigDetail.FindAllAsync(AIConfigDetail._.TenantId == currentUser.TenantId & AIConfigDetail._.ProjectId == ProjectId);
            if (!configDetails.Any())
            {
                return null;
            }

            var targetConfigDetail = GetTargetConfigDetail(configDetails, keyword);
            if (targetConfigDetail == null)
            {
                return null;
            }

            var fileList = JsonHelper.ToJsonEntity<List<ConfigFileDto>>(targetConfigDetail.File);

            return new ReplayContentDto
            {
                ReplyContent = targetConfigDetail.ReplyContent,
                FileList = fileList == null ? new List<ConfigFileDto>() : fileList
            };
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="configDetails"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>

        private AIConfigDetail GetTargetConfigDetail(IList<AIConfigDetail> configDetails, string keyword)
        {
            foreach (var configDetail in configDetails)
            {
                if (string.IsNullOrWhiteSpace(configDetail.Keyword))
                {
                    continue;
                }
                var keywords = configDetail.Keyword.Split(',', StringSplitOptions.RemoveEmptyEntries);
                foreach (var keywordItem in keywords)
                {
                    if (keyword.Contains(keywordItem))
                    {
                        return configDetail;
                    }
                }
            }
            return null;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public async Task<bool> ShowAIAssistant(UserTicket currentUser)
        {
            var configDetailCount = await AIConfigDetail.FindCountAsync(AIConfigDetail._.TenantId == currentUser.TenantId);
            if (configDetailCount > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}